package com.copc.common.handler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.convert.Convert;
import com.copc.common.constants.HttpStatus;
import com.copc.common.exception.CommonException;
import com.copc.common.util.ResultCommon;
import com.copc.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Resource
    private transient MessageSource messageSource;


    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResultCommon handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("请求地址'{}',发生未知异常.", request.getRequestURI(), e);
        return getValidResponse(HttpStatus.ERROR,e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResultCommon handleException(Exception e, HttpServletRequest request) {
        log.error("请求地址'{}',发生系统异常.", request.getRequestURI(), e);
        return getValidResponse(HttpStatus.ERROR,e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(CommonException.class)
    public ResultCommon handleCommonException(CommonException e, HttpServletRequest request) {
        log.error("请求地址'{}',发生系统异常.", request.getRequestURI(), e);
        return getValidResponse(e.getCode(),e.getMessage());
    }

    public ResultCommon getValidResponse(Integer code, String message) {
        return getValidResponse(Convert.toStr(code),message);
    }

    public ResultCommon getValidResponse(String codeStr, String message) {
        String code = cutString(codeStr, "{", "}");
        log.info("发生校验异常！原因是:{}", message.concat(String.format(" [biz_code=%s]", code)));
        return new ResultCommon(code, message);
    }


    public String cutString(String str, String start, String end) {
        if (StringUtils.isBlank(str)) {
            return str;
        }

        int startNum = str.indexOf(start) + 1;
        int endNum = str.lastIndexOf(end);

        if (startNum == 0 || endNum == -1) {
            return str;
        }

        String substring = str.substring(startNum, endNum);
        return substring;
    }

}

